package com.fine.hair.manage.controller;

import com.fine.hair.comm.utils.ApiResponse;
import com.fine.hair.comm.utils.MyStatus;
import com.fine.hair.comm.utils.Utils;
import com.fine.hair.manage.config.FileUploadConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件上传控制类
 *
 * @author junelee
 * @date 2020/3/20 20:21
 */
@RestController
@CrossOrigin
@RequestMapping("/file/")
@Api( tags = ("file-Controller 文件上传的相关接口"))
public class FileController {

    /**
     * 上传地址
     */
    private final FileUploadConfig fileUploadConfig;

    public FileController(FileUploadConfig fileUploadConfig) {
        this.fileUploadConfig = fileUploadConfig;
    }

    @ApiOperation(value = "单文件上传", notes = "单文件上传，rename 默认不重命名")
    @PostMapping(value = "upload/one", headers = "content-type=multipart/form-data")
    public ApiResponse uploadOne(@RequestParam(value = "file") MultipartFile mf, HttpServletRequest request) throws IOException {
        if (mf.isEmpty()) {
            return ApiResponse.ofStatus(MyStatus.FAILED);
        }

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String TimeDir = sdf.format(date);
        String realPath = fileUploadConfig.getLocation() + TimeDir;
        File file = new File(realPath);
        // 没有目录就创建
        if (!file.exists()) {
            file.mkdirs();
        }
        // 判断文件大小
        String filename = mf.getOriginalFilename();
        // 获取文件后缀
        String ext = filename.substring(filename.lastIndexOf("."), filename.length());
        // 检查文件类型
        if (!Utils.checkExt(fileUploadConfig.getAllowExt(), ext)) {
            return ApiResponse.ofStatus(MyStatus.FAILED);
        }
        // 默认不重命名
        String uploadFileName = Utils.generateString(filename);
        // 重命名文件 目标文件
        File targetFile = new File(realPath, uploadFileName);
        System.out.println(">>>>>>>>>>>>>>>>>>>>图片路径为" + realPath);
        System.out.println(fileUploadConfig.toString());
        //开始从源文件拷贝到目标文件
        //传图片一步到位
        mf.transferTo(targetFile);
        //拼接数据
        String imgstr = Utils.getBasePath(request) + fileUploadConfig.getVirtualAccessPath() + TimeDir + File.separator + uploadFileName;

        return ApiResponse.ofSuccess(imgstr);

    }

}
